package com.druid.common.config.secutity;

import com.druid.enums.ResponseDataEnums;
import com.druid.model.ResponseData;
import com.druid.util.UtilForHttpServletData;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证出错时处理
 */
@Log4j2
@Component("myAuthenticationFailHandler")
public class MyAuthenticationFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {

        ResponseDataEnums responseDataEnums = ResponseDataEnums.RESPONSE_FAIL_AUTHENTICATION;

        if (e.getCause() instanceof DisabledException) {
            responseDataEnums = ResponseDataEnums.RESPONSE_FAIL_DISABLED;
        } else if (e.getCause() instanceof BadCredentialsException) {
            responseDataEnums = ResponseDataEnums.RESPONSE_FAIL_USERNAMEORPASSWORD_NOTFOUND;
        }
        UtilForHttpServletData.responseDataForHttp( httpServletResponse, ResponseData.FAILURE(responseDataEnums) );

    }
}
